//
//  CoverManager.m
//  IOS7MEMTEST
//
//  Created by Eric on 13-10-15.
//  Copyright (c) 2013年 Eric. All rights reserved.
//

#import "CoverManager.h"
@interface CoverManager()
@property CGRect originRect;//theSuperView的原始Frame,未显示出键盘时的Frame
@property(nonatomic,copy) NSNotification *lastNofi;
@end
@implementation CoverManager
NSNotification *lastNoti = nil;
//与键盘的距离

-(id)initWithUIView:(UIView*)aView
{
    self = [super init];
    if(self)
    {
        self.theView = aView;
        [self registKeyboradNotificaiton];
        if(!_theSuperView) self.theSuperView = self.theView.superview;
        self.originRect = self.theSuperView.frame;
        self.keyboardOffset = 10;

    }
    return self;
}
-(void)clean
{
    self.theSuperView = nil;
    self.theView =  nil;
}
-(void)registKeyboradNotificaiton
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
-(void)removeKeyboradNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)setTheSuperView:(UIView *)theSuperView
{
    _theSuperView = theSuperView;
    self.originRect = _theSuperView.frame;
    
}
- (void)keyboardFrameWillChange:(NSNotification *)notification
{
    if(notification) self.lastNofi = notification;
    //WKDebug(@"keyboardFrameWillChange,theView = %d isF=%d",_theView.tag,_theView.isFirstResponder);
    if([self checkViewFocused])
    {
        [self runWithNotification:notification];
    }
    else
    {
        if((!notification && _lastNofi) )
        {
            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:_lastNofi.userInfo];
            [dict setObject:@(0.25f) forKey:UIKeyboardAnimationDurationUserInfoKey];
            NSNotification *noti =[NSNotification notificationWithName:_lastNofi.name object:_lastNofi.object userInfo:dict];
            [self runWithNotification:noti];
        }
    }
}

- (BOOL)checkViewFocused {
    if (self.isViewFocused != nil) {
        return self.isViewFocused(self.theView);
    }
    else {
        return self.theView.isFirstResponder;
    }
}

-(void)runWithNotification:(NSNotification*)notification
{
    if(notification)
    {
        CGRect keyBoardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat animationDuration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
        UIViewAnimationOptions curve = [notification.userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];
        
        if(keyBoardRect.origin.y >= [UIScreen mainScreen].bounds.size.height)
        {
            //移回原位
            [UIView animateWithDuration:animationDuration delay:0 options:curve animations:^{
                CGRect rect = _originRect;
                if(!CGRectEqualToRect(_recoverRect, CGRectZero)) rect = _recoverRect;
                [_theSuperView setFrame:CGRectMake(rect.origin.x, rect.origin.y , rect.size.width, rect.size.height)];
            } completion:nil];
        }
        else
        {
            //根据theView位置计算superView需要停留的位置
            __block CGRect theViewRect = [self getRectToWindow:_theView];
            __block CGFloat differenceHeight = theViewRect.origin.y + theViewRect.size.height + _keyboardOffset - keyBoardRect.origin.y ;//被键盘遮挡的高度数
 //           WKDebug(@"ddifferenceHeight = %f",differenceHeight);
//            if(differenceHeight > 0 || _theSuperView.frame.origin.y - differenceHeight < _originRect.origin.y)//吸附
            if(differenceHeight > 0 )
            {
                [UIView animateWithDuration:animationDuration
                                      delay:0
                                    options:curve
                                 animations:^{
                                     if ([_theSuperView isKindOfClass:[UIScrollView class]]) {
                                         CGRect scrollSubViewFrame = [_theView convertRect:_theView.bounds toView:_theSuperView];
                                         scrollSubViewFrame.size.height += _keyboardOffset;
                                         [((UIScrollView *)_theSuperView) scrollRectToVisible:scrollSubViewFrame animated:NO];
                                         
                                         // 重新计算differenceHeight
                                         theViewRect = [self getRectToWindow:_theView];
                                         differenceHeight = theViewRect.origin.y + theViewRect.size.height + _keyboardOffset - keyBoardRect.origin.y ;
                                     }
                                     
                                     [_theSuperView setFrame:CGRectMake(_theSuperView.frame.origin.x, _theSuperView.frame.origin.y - differenceHeight, _theSuperView.frame.size.width, _theSuperView.frame.size.height)];
                } completion:nil];
            }
        }
    }
}
-(void)goBackToOriginPosition
{
    
}
-(void)refresh
{
    [self keyboardFrameWillChange:nil];
}
-(CGRect)getRectToWindow:(UIView*)view
{
    CGRect rectInWindow = CGRectZero;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    
    rectInWindow = [view.superview convertRect:view.frame toView:window];
    return rectInWindow;
}

-(void)releaseThem
{
    self.theView = nil;
    self.theSuperView = nil;
}
-(void)dealloc
{
    [self releaseThem];
    [self removeKeyboradNotification];
    
}
@end
